angular.module('U9ImPDA.controllers')

.controller('LoginCtrl', ['$scope', 'AppManager', 'imanDialog', 'User', 'Help', 'LfRfid',
    function($scope, AppManager, imanDialog, User, Help, LfRfid) {
        $scope.data = {
            activeIndex: 1,
            usercode: '',
            password: '',
            autologin: false
        };

        $scope.clickTab = function(index) {
            $scope.data.activeIndex = index;
        };
        $scope.signin = function() {
            imanDialog.showLoading();
            User.signin(
                $scope.data.usercode,
                $scope.data.password,
                $scope.data.autologin
            ).then(function() {
                Help.goAsRoot('home');
            }).finally(function() {
                imanDialog.hideLoading();
            });
        };

        $scope.$on('$ionicView.afterEnter', function() {
            LfRfid.open();
        });
        $scope.$on('$ionicView.beforeLeave', function() {
            LfRfid.close();
        });
        $scope.$on('$destroy', function() {
            LfRfid.close();
        });
        var doubleScan = '';
        $scope.$on('LFRFID.DataReceived', function(e, data) {
            if ($scope.data.activeIndex !== 2) {
                return;
            }
            imanDialog.showLoading();
            if (doubleScan !== data) {
                doubleScan = data;
                User.signinScan(data).then(function() {
                    doubleScan = '';
                    Help.goAsRoot('home');
                }).finally(function() {
                    doubleScan = '';
                    imanDialog.hideLoading();
                });
            }
        });
    }
]);
